/**
 
 * 
 */
package nl.boektrust.btsoep.server;

import static com.google.appengine.api.taskqueue.TaskOptions.Builder.withUrl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nl.boektrust.btsoep.shared.model.BinaryAsset;
import nl.boektrust.btsoep.shared.model.ImageReferenceTypeCode;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;

/**
 * @author rao3
 *
 * the implementation of the server that can serve XML requests to Koppelvlak bookstores. 
 */
public class UploadImageFile extends HttpServlet {
	private boolean isObjectifyServiceRegistered = false;
	private ServletContext context;
	PersistentServiceImpl persistentServiceImpl = new PersistentServiceImpl();


	
	ServletContext getContext() {
		return this.context;
	}

	public void init() throws ServletException {
		context = getServletContext();
		//System.err.println("Real Path = " + context.getRealPath("/"));
	}

	/**
	 * 
	 */
	public UploadImageFile() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @param delegate
	 */
	public UploadImageFile(Object delegate) {
		//super(delegate);
		// TODO Auto-generated constructor stub
	}
	
	
	public void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws ServletException, IOException  
	{
	    System.err.println("doPost on uploadImageFile");

	    BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
		blobstoreService.getUploadedBlobs(request);
		System.out.println("get uploads getUploadedBlobs finished");
	    Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(request);
	    System.out.println("received "+blobs.size()+" blobs");

	    BlobKey theBlobKey = null;
		for (BlobKey blobKey : blobs.get("imageFile")) {
		    System.out.println("get blobkey, result: "+blobKey.getKeyString());
		    theBlobKey = blobKey;
		}

		String recordReference = request.getParameter("recordReference");
		String imageType = request.getParameter("imageType");
		String urlString = request.getParameter("urlString");
		if (recordReference != null) System.out.println("UploadImageFile: recordreference = "+recordReference);
		if (imageType != null) System.out.println("UploadImageFile: imageType = "+imageType);
		if (urlString != null) System.out.println("UploadImageFile: urlString = "+urlString);

		if (theBlobKey == null) {
		    System.out.println("redirect to /: ");

		    response.sendRedirect("/");

		} else {
		    System.out.println("redirect to /serve: ");

		    BinaryAsset b = new BinaryAsset();
			b.setOriginalUrl(urlString);
			b.setBlobKey(theBlobKey);
			ImageReferenceTypeCode imageTypeCode = ImageReferenceTypeCode.UNDEFINED;
			if (imageType.toLowerCase().equals("frontcover")) imageTypeCode = ImageReferenceTypeCode.FRONTCOVER;
			else if (imageType.toLowerCase().equals("backcover")) imageTypeCode = ImageReferenceTypeCode.BACKCOVER;
			b.setImageReferenceTypeCode(imageTypeCode);
			b.setRecordReference(new Long(recordReference));
			persistentServiceImpl.persistBinaryAsset(b);
			ImagesService imagesService = (ImagesService) ImagesServiceFactory.getImagesService();
			System.out.println("Resulting URL: " + imagesService.getServingUrl(theBlobKey));
			response.setContentType("text/html");
			response.getOutputStream().print("<html><body>Image toegevoegd aan boek met ISBN / RecordReference "+recordReference+":<p><img src=\""+imagesService.getServingUrl(theBlobKey)+"\"/><p></body></html>");
			response.getOutputStream().close();
			//response.sendRedirect("/serve?blob-key=" + theBlobKey.getKeyString());

		}
		
		/*
		 * get raw XML from the inputstream. 
		 */
		
		Queue queue = QueueFactory.getQueue("images");
		queue.add(withUrl("/importimagefiletask").param("urlString", urlString).param("recordReference",recordReference).param("imageType", imageType));
		response.setContentType("text/plain");
		response.getOutputStream().print("Added image update at URL "+urlString+" to task queue"+"images");
		response.getOutputStream().close();
	} 
	
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {
		doPost(request, response);
	}


}
